import logging
import os
from datetime import datetime
from config.settings import LOG_LEVEL, SCAN_PATH

def setup_logger(name: str = 'app') -> logging.Logger:
    """设置日志记录器
    
    Args:
        name: 日志记录器名称，默认为'app'
    
    Returns:
        配置好的日志记录器
    """
    # 创建logger
    logger = logging.getLogger(name)
    logger.setLevel(getattr(logging, LOG_LEVEL))
    
    # 避免重复添加handler
    if not logger.handlers:
        # 创建console handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(getattr(logging, LOG_LEVEL))
        
        # 创建logs文件夹（如果不存在）
        logs_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'logs')
        os.makedirs(logs_dir, exist_ok=True)
        
        # 从SCAN_PATH中提取盘符
        drive_letter = os.path.splitdrive(SCAN_PATH)[0] if os.path.splitdrive(SCAN_PATH)[0] else 'unknown'
        drive_letter = drive_letter.replace(':', '')  # 移除冒号
        
        # 生成日志文件名：扫描盘符-scan_log-时间
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        log_filename = f"{drive_letter}-scan_log-{timestamp}.log"
        log_file_path = os.path.join(logs_dir, log_filename)
        
        # 创建file handler
        file_handler = logging.FileHandler(log_file_path, encoding='utf-8')
        file_handler.setLevel(getattr(logging, LOG_LEVEL))
        
        # 设置格式
        formatter = logging.Formatter(
            '[%(levelname)s] %(asctime)s - %(name)s - %(message)s'
        )
        console_handler.setFormatter(formatter)
        file_handler.setFormatter(formatter)
        
        # 添加handler
        logger.addHandler(console_handler)
        logger.addHandler(file_handler)
    
    return logger